package com.hospital.controller;

import com.hospital.common.Result;
import com.hospital.common.UserRole;
import com.hospital.entity.*;
import com.hospital.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.time.LocalDate;
import java.util.ArrayList;

/**
 * 管理员专用控制器（系统管理功能）
 *
 * @author Hospital Management System
 */
@Api(tags = "系统管理（管理员专用）")
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {

    private final AuthService authService;
    private final UserService userService;
    private final DepartmentService departmentService;
    private final WardService wardService;
    private final MedicineService medicineService;
    private final ScheduleService scheduleService;
    private final RegistrationService registrationService;
    private final PasswordEncoder passwordEncoder;

    // ==================== 用户管理 ====================
    
    @ApiOperation("获取用户列表")
    @GetMapping("/users")
    public Result<Object> getUsers(
            @ApiParam("搜索关键词") @RequestParam(required = false) String keyword,
            @ApiParam("用户角色") @RequestParam(required = false) Integer role,
            @ApiParam("用户状态") @RequestParam(required = false) Integer status,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "20") Integer size) {
        // if (!isAdmin()) {
        //     return Result.error("权限不足，仅管理员可访问");
        // }
        
        Object result = userService.getUsersWithPagination(keyword, role, status, page, size);
        return Result.success(result);
    }

    @ApiOperation("添加用户")
    @PostMapping("/user")
    public Result<Void> addUser(@Validated @RequestBody User user) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        // 验证必填字段
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            return Result.error("密码不能为空");
        }
        
        // 对密码进行加密
        String encryptedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encryptedPassword);
        
        userService.save(user);
        return Result.success(null, "用户添加成功");
    }

    @ApiOperation("更新用户信息")
    @PutMapping("/updateUserInfo")
    public Result<User> updateUserInfo(@Validated @RequestBody User user) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        // 获取原始用户信息
        User existingUser = userService.getById(user.getId());
        if (existingUser == null) {
            return Result.error("用户不存在");
        }
        
        // 保持原有角色不变
        user.setRole(existingUser.getRole());
        
        // 如果是医生，需要处理职称和学历的转换
        if (UserRole.DOCTOR.equals(existingUser.getRole())) {
            // 转换职称（数字到文本）
            if (user.getTitle() != null) {
                user.setTitle(convertTitleToText(user.getTitle()));
            }
            
            // 转换学历（数字到文本）
            if (user.getEducation() != null) {
                user.setEducation(convertEducationToText(user.getEducation()));
            }
        }
        
        // 如果密码为空，保持原密码不变
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            user.setPassword(existingUser.getPassword());
        }
        
        // 更新用户信息
        userService.updateById(user);
        
        // 获取更新后的用户信息
        User updatedUser = userService.getById(user.getId());
        return Result.success(updatedUser, "用户信息更新成功");
    }

    @ApiOperation("获取用户详情")
    @GetMapping("/user/{userId}")
    public Result<User> getUserDetail(@PathVariable Long userId) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        User user = userService.getById(userId);
        return Result.success(user);
    }

    @ApiOperation("重置用户密码")
    @PutMapping("/user/{userId}/reset-password")
    public Result<Void> resetUserPassword(@PathVariable Long userId) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        userService.resetPassword(userId);
        return Result.success(null, "密码重置成功");
    }

    @ApiOperation("修改用户状态")
    @PutMapping("/user/{userId}/status")
    public Result<Void> changeUserStatus(
            @PathVariable Long userId,
            @RequestParam(required = false) Integer status,
            @RequestBody(required = false) Map<String, Object> body) {
        
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        // 如果status为null，尝试从请求体获取
        if (status == null && body != null) {
            status = (Integer) body.get("status");
        }
        
        // 参数验证
        if (status == null) {
            return Result.error("状态参数不能为空");
        }
        if (status != 0 && status != 1) {
            return Result.error("无效的状态值");
        }
        
        userService.changeStatus(userId, status);
        return Result.success(null, "用户状态修改成功");
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/user/{userId}")
    public Result<Void> deleteUser(@PathVariable Long userId) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        userService.removeById(userId);
        return Result.success(null, "用户删除成功");
    }

    // ==================== 医生管理 ====================
    
    @ApiOperation("获取医生列表")
    @GetMapping("/doctors")
    public Result<Map<String, Object>> getDoctors(
            @ApiParam("搜索关键词") @RequestParam(required = false) String keyword,
            @ApiParam("科室ID") @RequestParam(required = false) Long departmentId,
            @ApiParam("状态") @RequestParam(required = false) Integer status,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "20") Integer size) {
        
        // if (!isAdmin()) {
        //     return Result.error("权限不足，仅管理员可访问");
        // }
        
        Map<String, Object> result = userService.getDoctorsWithPagination(keyword, departmentId, status, page, size);
        return Result.success(result);
    }

    @ApiOperation("添加医生")
    @PostMapping("/doctor")
    public Result<Void> addDoctor(@Validated @RequestBody User doctor) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        // 验证必填字段
        if (doctor.getPassword() == null || doctor.getPassword().trim().isEmpty()) {
            return Result.error("密码不能为空");
        }
        
        doctor.setRole(UserRole.DOCTOR);
        
        // 转换职称（数字到文本）
        if (doctor.getTitle() != null) {
            doctor.setTitle(convertTitleToText(doctor.getTitle()));
        }
        
        // 转换学历（数字到文本）
        if (doctor.getEducation() != null) {
            doctor.setEducation(convertEducationToText(doctor.getEducation()));
        }
        
        // 对密码进行加密
        String encryptedPassword = passwordEncoder.encode(doctor.getPassword());
        doctor.setPassword(encryptedPassword);
        
        userService.save(doctor);
        return Result.success(null, "医生添加成功");
    }

    @ApiOperation("更新医生信息")
    @PutMapping("/doctor")
    public Result<Void> updateDoctor(@Validated @RequestBody User doctor) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        doctor.setRole(UserRole.DOCTOR);
        
        // 转换职称（数字到文本）
        if (doctor.getTitle() != null) {
            doctor.setTitle(convertTitleToText(doctor.getTitle()));
        }
        
        // 转换学历（数字到文本）
        if (doctor.getEducation() != null) {
            doctor.setEducation(convertEducationToText(doctor.getEducation()));
        }
        
        // 如果密码为空或null，则不更新密码字段
        if (doctor.getPassword() == null || doctor.getPassword().isEmpty()) {
            // 获取原始用户信息，保持密码不变
            User existingUser = userService.getById(doctor.getId());
            if (existingUser != null) {
                doctor.setPassword(existingUser.getPassword());
            }
        }
        
        userService.updateById(doctor);
        return Result.success(null, "医生信息更新成功");
    }

    @ApiOperation("删除医生")
    @DeleteMapping("/doctor/{doctorId}")
    public Result<Void> deleteDoctor(@PathVariable Long doctorId) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        userService.removeById(doctorId);
        return Result.success(null, "医生删除成功");
    }

    @ApiOperation("获取医生详情")
    @GetMapping("/doctor/{doctorId}")
    public Result<User> getDoctorDetail(@PathVariable Long doctorId) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        User doctor = userService.getDoctorDetail(doctorId);
        return Result.success(doctor);
    }

    // ==================== 管理员管理 ====================
    
    @ApiOperation("获取管理员列表")
    @GetMapping("/admins")
    public Result<List<User>> getAdmins(@ApiParam("搜索关键词") @RequestParam(required = false) String keyword) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        List<User> admins = userService.getAdmins(keyword);
        return Result.success(admins);
    }

    @ApiOperation("添加管理员")
    @PostMapping("/admin")
    public Result<Void> addAdmin(@Validated @RequestBody User admin) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        // 验证必填字段
        if (admin.getPassword() == null || admin.getPassword().trim().isEmpty()) {
            return Result.error("密码不能为空");
        }
        
        admin.setRole(UserRole.ADMIN);
        
        // 对密码进行加密
        String encryptedPassword = passwordEncoder.encode(admin.getPassword());
        admin.setPassword(encryptedPassword);
        
        userService.save(admin);
        return Result.success(null, "管理员添加成功");
    }

    @ApiOperation("更新管理员信息")
    @PutMapping("/admin")
    public Result<Void> updateAdmin(@Validated @RequestBody User admin) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        admin.setRole(UserRole.ADMIN);
        userService.updateById(admin);
        return Result.success(null, "管理员信息更新成功");
    }

    @ApiOperation("删除管理员")
    @DeleteMapping("/admin/{adminId}")
    public Result<Void> deleteAdmin(@PathVariable Long adminId) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        userService.removeById(adminId);
        return Result.success(null, "管理员删除成功");
    }

    // ==================== 科室管理 ====================
    
    @ApiOperation("添加科室")
    @PostMapping("/department")
    public Result<Void> addDepartment(@Validated @RequestBody Department department) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        departmentService.save(department);
        return Result.success(null, "科室添加成功");
    }

    @ApiOperation("更新科室信息")
    @PutMapping("/department")
    public Result<Void> updateDepartment(@Validated @RequestBody Department department) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        departmentService.updateById(department);
        return Result.success(null, "科室信息更新成功");
    }

    @ApiOperation("删除科室")
    @DeleteMapping("/department/{departmentId}")
    public Result<Void> deleteDepartment(@PathVariable Long departmentId) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        departmentService.removeById(departmentId);
        return Result.success(null, "科室删除成功");
    }

    // ==================== 病房管理 ====================
    
    @ApiOperation("添加病房")
    @PostMapping("/ward")
    public Result<Void> addWard(@Validated @RequestBody Ward ward) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        wardService.save(ward);
        return Result.success(null, "病房添加成功");
    }

    @ApiOperation("更新病房信息")
    @PutMapping("/ward")
    public Result<Void> updateWard(@Validated @RequestBody Ward ward) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        wardService.updateById(ward);
        return Result.success(null, "病房信息更新成功");
    }

    @ApiOperation("删除病房")
    @DeleteMapping("/ward/{wardId}")
    public Result<Void> deleteWard(@PathVariable Long wardId) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        wardService.removeById(wardId);
        return Result.success(null, "病房删除成功");
    }

    // ==================== 药品管理 ====================
    
    @ApiOperation("添加药品")
    @PostMapping("/medicine")
    public Result<Void> addMedicine(@Validated @RequestBody Medicine medicine) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        medicineService.save(medicine);
        return Result.success(null, "药品添加成功");
    }

    @ApiOperation("更新药品信息")
    @PutMapping("/medicine")
    public Result<Void> updateMedicine(@Validated @RequestBody Medicine medicine) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        medicineService.updateById(medicine);
        return Result.success(null, "药品信息更新成功");
    }

    @ApiOperation("删除药品")
    @DeleteMapping("/medicine/{medicineId}")
    public Result<Void> deleteMedicine(@PathVariable Long medicineId) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        medicineService.removeById(medicineId);
        return Result.success(null, "药品删除成功");
    }

    @ApiOperation("更新药品状态")
    @PutMapping("/medicine/{medicineId}/status")
    public Result<Void> updateMedicineStatus(@PathVariable Long medicineId, @RequestParam Integer status) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        medicineService.updateMedicineStatus(medicineId, status);
        return Result.success(null, "药品状态更新成功");
    }

    @ApiOperation("批量更新过期药品状态")
    @PutMapping("/medicines/update-expired")
    public Result<Void> updateExpiredMedicineStatus() {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        medicineService.updateExpiredMedicineStatus();
        return Result.success(null, "过期药品状态更新成功");
    }

    // ==================== 系统管理 ====================
    
    @ApiOperation("系统统计信息")
    @GetMapping("/statistics")
    public Result getSystemStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 用户统计
        statistics.put("totalUsers", userService.count());
        statistics.put("newUsersToday", userService.countNewUsersToday());
        
        // 医生统计
        statistics.put("totalDoctors", userService.countByRole(UserRole.DOCTOR));
        statistics.put("activeDoctors", scheduleService.countActiveDoctorsToday());
        
        // 挂号统计
        statistics.put("todayRegistrations", registrationService.countTodayRegistrations());
        statistics.put("registrationGrowth", registrationService.calculateRegistrationGrowth());
        
        return Result.success(statistics);
    }

    @ApiOperation("系统配置管理")
    @GetMapping("/config")
    public Result<Object> getSystemConfig() {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        // TODO: 实现系统配置功能
        return Result.success(null, "系统配置获取成功");
    }

    @ApiOperation("更新系统配置")
    @PutMapping("/config")
    public Result<Void> updateSystemConfig(@RequestBody Object config) {
        if (!isAdmin()) {
            return Result.error("权限不足，仅管理员可访问");
        }
        
        // TODO: 实现系统配置更新功能
        return Result.success(null, "系统配置更新成功");
    }

    /**
     * 获取挂号趋势数据
     */
    @GetMapping("/registration/trend")
    public Result getRegistrationTrend(@RequestParam(defaultValue = "7") Integer days) {
        if (days != 7 && days != 30 && days != 90) {
            return Result.error("只支持查询7天、30天或90天的趋势");
        }
        
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);
        
        Map<String, Object> trend = registrationService.getRegistrationTrend(startDate, endDate);
        return Result.success(trend);
    }

    /**
     * 获取科室就诊分布数据
     */
    @GetMapping("/department/distribution")
    public Result getDepartmentDistribution() {
        List<Map<String, Object>> distribution = registrationService.getDepartmentDistribution();
        return Result.success(distribution);
    }

    /**
     * 获取实时挂号数据
     */
    @GetMapping("/registration/realtime")
    public Result getRealtimeRegistrations() {
        List<Map<String, Object>> realtimeData = registrationService.getRealtimeRegistrations();
        return Result.success(realtimeData);
    }

    /**
     * 获取系统预警信息
     */
    @GetMapping("/warnings")
    public Result getSystemWarnings() {
        List<Map<String, Object>> warnings = new ArrayList<>();
        
        // 检查药品库存预警
        List<Map<String, Object>> medicineWarnings = medicineService.checkLowStock();
        warnings.addAll(medicineWarnings);
        
        // TODO: 可以添加更多预警检查，如设备维护预警等
        
        return Result.success(warnings);
    }

    // ==================== 工具方法 ====================
    
    /**
     * 检查当前用户是否为管理员
     */
    private boolean isAdmin() {
        User currentUser = authService.getCurrentUser();
        return currentUser != null && UserRole.ADMIN.equals(currentUser.getRole());
    }

    /**
     * 转换职称数字为文本
     */
    private String convertTitleToText(String titleStr) {
        try {
            int title = Integer.parseInt(titleStr);
            switch (title) {
                case 1: return "主任医师";
                case 2: return "副主任医师";
                case 3: return "主治医师";
                case 4: return "住院医师";
                case 5: return "实习医师";
                default: return titleStr; // 如果不是数字或无法转换，返回原值
            }
        } catch (NumberFormatException e) {
            return titleStr; // 如果不是数字，返回原值
        }
    }

    /**
     * 转换学历数字为文本
     */
    private String convertEducationToText(String educationStr) {
        try {
            int education = Integer.parseInt(educationStr);
            switch (education) {
                case 1: return "博士";
                case 2: return "硕士";
                case 3: return "本科";
                case 4: return "大专";
                case 5: return "其他";
                default: return educationStr; // 如果不是数字或无法转换，返回原值
            }
        } catch (NumberFormatException e) {
            return educationStr; // 如果不是数字，返回原值
        }
    }
} 